<template>
  <div class="quiz">
    <div class="container">
      <div class="quiz-header">
        <h1>📝 在线答题</h1>
        <div class="student-info">
          <span>👤 {{ studentName }}</span>
        </div>
      </div>
      
      <div v-if="loading" class="loading">
        <p>正在加载题目...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="loadQuestions" class="btn">重新加载</button>
      </div>
      
      <div v-else-if="questions.length > 0" class="quiz-content">
        <div class="progress-bar">
          <div class="progress" :style="{ width: progressPercentage + '%' }"></div>
        </div>
        <p class="progress-text">已答题：{{ answeredCount }} / {{ questions.length }}</p>
        
        <div class="questions-container">
          <div 
            v-for="(question, index) in questions" 
            :key="question.id" 
            class="question-card"
          >
            <div class="question-number">第 {{ index + 1 }} 题</div>
            <div class="question-title">{{ question.question_content }}</div>
            
            <div class="options">
              <div 
                v-for="option in getOptions(question)" 
                :key="option.key"
                class="option"
                :class="{ selected: answers[question.id] === option.key }"
                @click="selectOption(question.id, option.key)"
              >
                <input 
                  type="radio" 
                  :id="`q${question.id}_${option.key}`"
                  :name="`question_${question.id}`"
                  :value="option.key"
                  v-model="answers[question.id]"
                >
                <label :for="`q${question.id}_${option.key}`">
                  {{ option.key }}. {{ option.text }}
                </label>
              </div>
            </div>
          </div>
        </div>
        
        <div class="submit-section">
          <button 
            @click="submitAnswers" 
            class="btn submit-btn"
            :disabled="!canSubmit || submitting"
          >
            {{ submitting ? '提交中...' : '提交答案' }}
          </button>
          <p v-if="!canSubmit" class="warning">
            请完成所有题目后再提交
          </p>
        </div>
      </div>
      
      <div v-else class="no-questions">
        <p>暂无题目，请联系老师添加题目。</p>
        <button @click="$router.push('/')" class="btn">返回首页</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Quiz',
  data() {
    return {
      studentName: '',
      classId: '',
      questions: [],
      answers: {},
      loading: true,
      error: null,
      submitting: false
    }
  },
  computed: {
    answeredCount() {
      return Object.keys(this.answers).length
    },
    progressPercentage() {
      if (this.questions.length === 0) return 0
      return (this.answeredCount / this.questions.length) * 100
    },
    canSubmit() {
      return this.answeredCount === this.questions.length
    }
  },
  async created() {
    // 检查学生信息
    this.studentName = sessionStorage.getItem('studentName')
    this.classId = sessionStorage.getItem('classId') || '1' // 默认为1班
    
    if (!this.studentName) {
      this.$router.push('/')
      return
    }
    
    await this.loadQuestions()
  },
  methods: {
    async loadQuestions() {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get('/api/questions')
        this.questions = response.data
        
        if (this.questions.length === 0) {
          this.error = '暂无题目可供练习'
        }
      } catch (error) {
        console.error('加载题目失败:', error)
        this.error = '加载题目失败，请检查网络连接'
      } finally {
        this.loading = false
      }
    },
    
    getOptions(question) {
      return [
        { key: 'A', text: question.option_a },
        { key: 'B', text: question.option_b },
        { key: 'C', text: question.option_c },
        { key: 'D', text: question.option_d }
      ].filter(option => option.text && option.text.trim() !== '')
    },
    
    selectOption(questionId, optionKey) {
      this.answers[questionId] = optionKey
      // 强制更新响应式数据
      this.$forceUpdate()
    },
    
    async submitAnswers() {
      if (!this.canSubmit || this.submitting) return
      
      this.submitting = true
      
      try {
        // 构造提交数据
        const submitData = {
          student_name: this.studentName,
          class_id: parseInt(this.classId),
          answers: Object.entries(this.answers).map(([questionId, selectedAnswer]) => ({
            questionId: parseInt(questionId),
            selectedAnswer: selectedAnswer
          }))
        }
        
        const response = await axios.post('/api/submit', submitData)
        
        // 将结果存储到sessionStorage
        sessionStorage.setItem('quizResult', JSON.stringify(response.data))
        
        // 跳转到结果页面
        this.$router.push('/result')
        
      } catch (error) {
        console.error('提交答案失败:', error)

        // 处理不同类型的错误
        if (error.response) {
          const status = error.response.status
          const message = error.response.data?.detail || '提交失败'

          if (status === 429) {
            // 姓名重复使用或请求过于频繁
            alert(`⚠️ ${message}`)
            // 如果是姓名重复使用错误，返回首页重新输入姓名
            if (message.includes('姓名在30分钟内已被使用')) {
              this.$router.push('/')
            }
          } else if (status === 400) {
            alert(`❌ 输入错误：${message}`)
          } else {
            alert(`❌ 提交失败：${message}`)
          }
        } else {
          alert('❌ 网络错误，请检查网络连接后重试')
        }
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
.quiz {
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.quiz::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>') repeat;
  pointer-events: none;
}

.quiz-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  flex-wrap: wrap;
  gap: 20px;
  position: relative;
  z-index: 1;
}

.quiz-header h1 {
  color: #fff;
  margin: 0;
  font-size: clamp(1.8rem, 4vw, 2.5rem);
  font-weight: 700;
  text-shadow: 0 4px 8px rgba(0,0,0,0.3);
  background: linear-gradient(45deg, #fff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.student-info {
  display: flex;
  justify-content: center;
  gap: 20px;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.9);
  background: rgba(255, 255, 255, 0.1);
  padding: 10px 20px;
  border-radius: 25px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.loading, .error, .no-questions {
  text-align: center;
  padding: 60px 40px;
  color: rgba(255, 255, 255, 0.9);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 18px;
  position: relative;
  z-index: 1;
}

.progress-bar {
  width: 100%;
  height: 12px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  overflow: hidden;
  margin-bottom: 15px;
  position: relative;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.progress-bar::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  animation: shimmer 2s ease-in-out infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #4CAF50, #45a049, #4CAF50);
  background-size: 200% 100%;
  animation: progressGlow 2s ease-in-out infinite;
  transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 20px;
  position: relative;
}

@keyframes progressGlow {
  0%, 100% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
}

.progress-text {
  text-align: center;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 40px;
  font-weight: 500;
  font-size: 16px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.questions-container {
  margin-bottom: 50px;
  position: relative;
  z-index: 1;
}

.question-number {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  padding: 8px 20px;
  border-radius: 25px;
  font-size: 14px;
  font-weight: 600;
  display: inline-block;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  position: relative;
  overflow: hidden;
}

.question-number::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.question-number:hover::before {
  left: 100%;
}

.question-title {
  color: #000000;
  font-size: 18px;
  font-weight: 900;
  line-height: 1.6;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.options {
  margin-top: 25px;
  display: grid;
  gap: 12px;
}

.option {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  margin: 0;
  border-radius: 15px;
  border: 2px solid rgba(255, 255, 255, 0.8);
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  min-height: 60px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.option::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.option:hover {
  background: rgba(255, 255, 255, 0.95);
  border-color: rgba(255, 255, 255, 0.9);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.option:hover label {
  color: #000000;
  font-weight: 500;
}

.option:hover::before {
  opacity: 1;
}

/* 选中状态样式 - 使用更兼容的方式 */
.option input[type="radio"]:checked {
  accent-color: #4CAF50;
}

.option input[type="radio"]:checked + label {
  font-weight: 600;
  color: #000000;
}

/* 通过JavaScript动态添加的选中状态类 */
.option.selected {
  background: rgba(76, 175, 80, 0.4) !important;
  border-color: #4CAF50 !important;
  box-shadow: 0 0 0 4px rgba(76, 175, 80, 0.3) !important;
  transform: scale(1.02) !important;
  position: relative;
}

.option.selected::before {
  content: '✓';
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #4CAF50;
  font-size: 24px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  animation: checkmark 0.3s ease-in-out;
}

@keyframes checkmark {
  0% { transform: translateY(-50%) scale(0); }
  50% { transform: translateY(-50%) scale(1.2); }
  100% { transform: translateY(-50%) scale(1); }
}

.option.selected label {
  color: #000000 !important;
  font-weight: 700 !important;
}

.option input[type="radio"] {
  margin-right: 15px;
  transform: scale(1.5);
  accent-color: #4CAF50;
  position: relative;
  z-index: 1;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

.option input[type="radio"]:checked {
  transform: scale(1.6);
  filter: drop-shadow(0 2px 6px rgba(76, 175, 80, 0.5));
}

.option label {
  flex: 1;
  cursor: pointer;
  margin: 0;
  color: #000000;
  font-weight: 400;
  line-height: 1.6;
  position: relative;
  z-index: 1;
  font-size: 16px;
}

.submit-section {
  text-align: center;
  padding: 40px 0;
  border-top: 2px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 1;
}

.submit-btn {
  font-size: 18px;
  padding: 18px 50px;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  box-shadow: 0 8px 25px rgba(76, 175, 80, 0.4);
  position: relative;
  overflow: hidden;
}

.submit-btn:hover {
  box-shadow: 0 12px 35px rgba(76, 175, 80, 0.5);
  background: linear-gradient(135deg, #45a049, #4CAF50);
}

.submit-btn::after {
  content: '📝';
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  transition: transform 0.3s ease;
}

.submit-btn:hover::after {
  transform: translateY(-50%) scale(1.2);
}

.warning {
  color: #ffeb3b;
  font-size: 16px;
  margin: 0;
  background: rgba(255, 235, 59, 0.1);
  padding: 12px 20px;
  border-radius: 10px;
  border: 1px solid rgba(255, 235, 59, 0.3);
  backdrop-filter: blur(5px);
  font-weight: 500;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

@media (max-width: 768px) {
  .quiz {
    padding: 15px;
  }
  
  .quiz-header {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
  
  .student-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .option {
    padding: 14px 16px;
  }
  
  .submit-btn {
    padding: 16px 40px;
    font-size: 16px;
  }
}
</style>